package com.chen.project.file_client.service.impl;


import com.chen.project.file_client.config.FileProps;
import com.chen.project.file_client.controller.FileInfoController;
import com.chen.project.file_client.service.HttpService;
import com.chen.project.file_client.utils.AESUtils;
import com.chen.project.file_client.utils.Base64Utils;
import com.chen.project.file_client.utils.RSAUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * HttpService的实现
 * @author AUSA
 */
@Service
public class HttpServiceImpl implements HttpService {

    @Resource
    private FileProps fileProps;

    @Override
    public String upload2Server(MultipartFile file, HttpServletResponse response) throws Exception {

        String result = "";
        // 创建http客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            // 构建请求
            URIBuilder uriBuilder = new URIBuilder(fileProps.getServer());
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("action", "upload"));
            uriBuilder.setParameters(params);

            // 创建 POST 请求
            HttpPost httpPost = new HttpPost(uriBuilder.build());

            // 原始文件名
            String fileOriName = file.getOriginalFilename();

            // 设置请求 header
            Map<String, String> headers = genHeaders();
            for (Map.Entry<String, String> e : headers.entrySet()) {
                httpPost.addHeader(e.getKey(), e.getValue());
            }

            //
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setCharset(Charset.forName("utf-8"));

            //加上此行代码解决返回中文乱码问题
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // 文件流
            multipartEntityBuilder.addBinaryBody(file.getName(), file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileOriName);

            // 生成请求体
            HttpEntity entity = multipartEntityBuilder.build();
            httpPost.setEntity(entity);

            // 执行提交，获取响应体
            HttpResponse executeResponse = httpClient.execute(httpPost);
            StatusLine statusLine = executeResponse.getStatusLine();
            if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                response.setStatus(statusLine.getStatusCode());
                return "error happened";
            }
            HttpEntity responseEntity = executeResponse.getEntity();
            if (responseEntity != null) {
                // 将响应体内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public void downloadFileFromServerByUuid(String uuid, HttpServletResponse response) {

        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        InputStream in = null;
        OutputStream out = null;
        try {
            // 构建请求
            URIBuilder uriBuilder = new URIBuilder(fileProps.getServer());
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("action", "downloadByUuid"));
            params.add(new BasicNameValuePair("uuid", uuid));
            uriBuilder.setParameters(params);
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            // 设置请求 header
            Map<String, String> headers = genHeaders();
            // 设置请求 header
            for (Map.Entry<String, String> e : headers.entrySet()) {
                httpGet.addHeader(e.getKey(), e.getValue());
            }

            // 执行请求，获取响应
            HttpResponse executeResponse = httpClient.execute(httpGet);

            StatusLine statusLine = executeResponse.getStatusLine();
            System.out.println("状态码：" + statusLine);

            if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                response.setStatus(statusLine.getStatusCode());
                return;
            }

            // 获取文件的类型
            Header contentTypeHeader = executeResponse.getFirstHeader("Content-Type");
            String mimeType = contentTypeHeader.getValue();
            response.setContentType(mimeType);

            // 获取文件的 disposition
            Header contentDispositionHeader = executeResponse.getFirstHeader("Content-Disposition");
            String disposition = contentDispositionHeader.getValue();
            response.setHeader("Content-Disposition", disposition);

            // 获取数字信封
            Header envelopeHeader = executeResponse.getFirstHeader("envelope");
            String envelope = envelopeHeader.getValue();
            System.out.println("数字信封：" + envelope);

            // 通过 RSA 私钥解密数字信封，得到 AES 密钥
            byte[] data = Base64Utils.decode(envelope);
            byte[] aesKeyBytes = RSAUtils.decryptByPrivateKey(data, FileInfoController.PRI_KEY);
            String aesKey = new String(aesKeyBytes);

            // 获取响应体的文件流
            HttpEntity entity = executeResponse.getEntity();
            in = entity.getContent();

            // 通过 AES 密钥解密文件流
            in = AESUtils.decryptFile(aesKey, in);

            out = response.getOutputStream();
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getFileInfoByUuid(String uuid) throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 GET 请求
        URIBuilder uriBuilder = new URIBuilder(fileProps.getServer());
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("action", "getFileInfoByUuid"));
        params.add(new BasicNameValuePair("uuid", uuid));
        uriBuilder.setParameters(params);
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 设置请求 header
        Map<String, String> headers = genHeaders();
        for (Map.Entry<String, String> e : headers.entrySet()) {
            httpGet.addHeader(e.getKey(), e.getValue());
        }

        // 提交请求，获取响应
        HttpResponse executeResponse = httpClient.execute(httpGet);
        HttpEntity entity = executeResponse.getEntity();
        String json = EntityUtils.toString(entity);
        return json;
    }

    @Override
    public String getFileInfoList() throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 GET 请求
        URIBuilder uriBuilder = new URIBuilder(fileProps.getServer());
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("action", "getFileInfoList"));
        uriBuilder.setParameters(params);
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 设置请求 header
        Map<String, String> headers = genHeaders();
        for (Map.Entry<String, String> e : headers.entrySet()) {
            httpGet.addHeader(e.getKey(), e.getValue());
        }

        // 提交请求，获取响应
        HttpResponse executeResponse = httpClient.execute(httpGet);
        HttpEntity entity = executeResponse.getEntity();
        String json = EntityUtils.toString(entity);
        System.out.println(json);

        return json;
    }

    /**
     * 随机生成请求头 X-SID、X-Signature
     *
     * @return
     * @throws Exception
     */
    private Map<String, String> genHeaders() throws Exception {

        // 生成 X-SID
        String sid = RandomStringUtils.randomAscii(5);

        // 生成 X-Signature
        String signature = RSAUtils.sign(sid.getBytes(), FileInfoController.PRI_KEY);

        Map<String, String> map = new HashMap<>(2);
        map.put("X-SID", sid);
        map.put("X-Signature", signature);
        return map;
    }
}
